# -*- coding: utf-8 -*-


import xml
import xml.etree.ElementTree as ET
import re
import sys
import warnings
import argparse
import os.path
warnings.filterwarnings("ignore")
"""
实现从xml文件中读取数据
"""
#全局唯一标识 
unique_id = 1
  
#遍历所有的节点 
def walkData(root_node, level, result_list): 
  global unique_id 
  temp_list =[unique_id, level, root_node.tag, root_node.attrib] 
  result_list.append(temp_list) 
  unique_id += 1
    
  #遍历每个子节点 
  children_node = root_node.getchildren() 
  if len(children_node) == 0: 
    return
  for child in children_node: 
    walkData(child, level + 1, result_list) 
  return
 
def getXmlData(file_name): 
  level = 1 #节点的深度从1开始 
  result_list = [] 
  root = ET.parse(file_name).getroot() 
  walkData(root, level, result_list) 
  
  return result_list 

def genDeclare(R,indentCount = 0):
    result = ""
    for x in R: 
        try:
            typeName = x[2]
            full_id = x[3]['{http://schemas.android.com/apk/res/android}id']
            searchObj = re.search( r'@\+id/(.*)', full_id, re.M|re.I)
            pure_id = searchObj.group(1)
            # 加入缩进控制
            indentStr = ""
            for i in range(0,indentCount):
                indentStr += "\t"
            result += "%s private var %s: %s? = null\r\n" % (indentStr,pure_id,typeName)
        except:
            pass
    return result

def genInitView(R,indentCount = 0):
    result = ""
    for x in R: 
        try:
            full_id = x[3]['{http://schemas.android.com/apk/res/android}id']
            searchObj = re.search( r'@\+id/(.*)', full_id, re.M|re.I)
            pure_id = searchObj.group(1)
            indentStr = ""
            for i in range(0,indentCount):
                indentStr += "\t"
            result += "%s%s = itemView?.findViewById(R.id.%s)\r\n" % (indentStr,pure_id,pure_id)
        except:
            pass
    return result
    
def openfile(filename):
    result = ""
    with open(filename,'r',encoding="utf-8") as f:
        result = f.read()
    return result

def getfilename(filename):
    result = filename
    indexSlant = -1
    try:
        indexSlant = filename.rindex("\\")
    except:
        pass
    if indexSlant == -1:
        try:
            indexSlant = filename.rindex("/")   
        except:     
            pass
    indexExt = -1
    try:
        indexExt = filename.rindex("xml")
    except:
        pass
    if indexExt != -1 and indexExt !=-1:
        result = filename[indexSlant + 1:indexExt-1]
    return result

def genWithLayoutFileName(layout_file_name):
     #'d:\\fenlei2.xml'
    if layout_file_name == "":
        return 
    template_file_name = 'template/TemplateListViewAdapter.kt'
    R = getXmlData(layout_file_name)   
    readtext = openfile(template_file_name)
    readtext = readtext.replace("[declare_statement]",genDeclare(R,1))
    readtext = readtext.replace("[init_view_statement]",genInitView(R,2))
    readtext = readtext.replace("[layoutname]",getfilename(layout_file_name))
    print(readtext)
    
    
def main(args):
    layout_file_name = ""
    if args.layout_path:
        layout_file_name = args.layout_path
    
    if os.path.exists(layout_file_name)!=True:
        print("该路径：%s 不存在" % layout_file_name)
        return
    
    if layout_file_name.endswith(".xml")!=True:
        print("后缀应为 xml：%s" % layout_file_name)
        return
        
    genWithLayoutFileName(layout_file_name)
    pass
    
if __name__ == '__main__':
     # 配置支持的参数
    parser = argparse.ArgumentParser("生成 RecyclerView Adapter 代码")
    parser.add_argument('--layout_path',help="设置 Adapter 布局的路径")
    if len(sys.argv) < 2:
        print("生成 RecyclerView Adapter 代码")
        print()
        print("  --layout_path: 设置 Adapter 布局的路径")
    else:    
        # 参数解析
        args = parser.parse_args()  
        main(args)
            
